package com.sitanyun.merchant.guide.frament.view.fragment;


import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.sitanyun.merchant.guide.R;
import com.sitanyun.merchant.guide.adapter.ScenHomeAdapter;
import com.sitanyun.merchant.guide.base.BaseFragment;
import com.sitanyun.merchant.guide.base.ToastUtil;
import com.sitanyun.merchant.guide.bean.ScenceHomeBean;
import com.sitanyun.merchant.guide.bean.UserVrBean;
import com.sitanyun.merchant.guide.frament.presenter.impl.ScenHomeFramentFPresenterImpl;
import com.sitanyun.merchant.guide.frament.view.inter.IScenHomeFramentFView;
import com.sitanyun.merchant.guide.url.Urls;
import com.sitanyun.merchant.guide.view.activity.PosterActivity;
import com.sitanyun.merchant.guide.view.activity.VrWebActivity;
import com.sitanyun.merchant.guide.weiht.DateUtils;
import com.sitanyun.merchant.guide.weiht.SharedPreferenceUtil;
import com.sitanyun.merchant.guide.weiht.WxShareUtils;
import com.tencent.imsdk.v2.V2TIMManager;
import com.tencent.imsdk.v2.V2TIMMessage;
import com.tencent.imsdk.v2.V2TIMSendCallback;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;

/**
 * 精品场景
 * A simple {@link Fragment} subclass.
 */
public class ScenHomeFrament extends BaseFragment implements IScenHomeFramentFView {


    @BindView(R.id.tv_title_str)
    TextView tvTitleStr;
    @BindView(R.id.rv_scen_home)
    RecyclerView rvScenHome;
    @BindView(R.id.company)
    TextView company;
    @BindView(R.id.tv_screen)
    TextView tvScreen;

    @BindView(R.id.tv_return)
    ImageView tvReturn;
    @BindView(R.id.scen_fh)
    ImageView scenFh;
    @BindView(R.id.oneyy)
    LinearLayout oneyy;
    @BindView(R.id.ll_todaytwo)
    LinearLayout llTodaytwo;
    private UserVrBean.CloudCustomDataBean cloudCustomDataBean = new UserVrBean.CloudCustomDataBean();

    private ScenHomeFramentFPresenterImpl mIScenHomeFramentFPresenter;
    private ScenceHomeBean scenceHomeBean;
    private ScenHomeAdapter scenHomeAdapter;
    private PopupWindow popupWindow;
    private Bitmap bitmap;
    private String picUrl;
    private String sceneUrl;
    private String sceneId;
    private String scenname;
    private String  storename;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 10:
                    if (bitmap != null) {
                        WxShareUtils.shareWxMin(getActivity(), "wx7cb638590873ca35"
                                , "VR全景逛，让您身临其境，乐享其中！", Urls.urls + "/v-show/index.html?" + sceneUrl,
                                "" + scenceHomeBean.getData().getMerchantName()+"("+scenname+")",
                                "gh_5a0ad3d58ce7",
                                "pages/vr/vr?sceneId=" + sceneId
                                        + "&staffId=" + SharedPreferenceUtil.getStringData("staffid") + "&shareStaffId=" + SharedPreferenceUtil.getStringData("staffid")
                                , bitmap);

                    }
                    break;
            }
        }
    };


    @Override
    public int getLayoutId() {
        return R.layout.fragment_scen_home_frament;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        tvTitleStr.setText("精品场景");
        mIScenHomeFramentFPresenter = new ScenHomeFramentFPresenterImpl(this);
        mIScenHomeFramentFPresenter.getLscenhome("sortType");
        tvScreen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                scenFh.animate().setDuration(500).rotation(180).start();
                initpopu(v);
            }
        });
    }

    @Override
    public void initView() {
        //创建布局管理
        rvScenHome.getItemAnimator().setChangeDuration(0);// 通过设置动画执行时间为0来解决闪烁问题
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvScenHome.setLayoutManager(layoutManager);
        scenHomeAdapter = new ScenHomeAdapter(getActivity());
        rvScenHome.setAdapter(scenHomeAdapter);
        scenHomeAdapter.notifyDataSetChanged();
        //跳转
        scenHomeAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.wx_shar:

                       if (scenceHomeBean.getData().getList().get(position).getEndTime()==null){
                           return;
                       }else {
                           DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                           Date one;
                           Date two;
                           long day = 0;
                           long hour = 0;
                           long min = 0;
                           long sec = 0;
                           try {
                               //1 当前时间 ，2到期时间
                               Date curDate = new Date(System.currentTimeMillis());//获取当前时间
                               String str = df.format(curDate);
                               one = df.parse(str);
                               two = df.parse(scenceHomeBean.getData().getList().get(position).getEndTime());
                               long time1 = one.getTime();
                               long time2 = two.getTime();
                               long diff;
                               if (time1 > time2) {
                               ToastUtil.showToast(getActivity(),"该场景已过期");
                                  return;

                               }
                           } catch (ParseException e) {
                               e.printStackTrace();
                           }
                       }
                        if (DateUtils.isFastClick()) {
                            return ;
                        }

                        showBottomDialog(position);

                        break;
                    case R.id.scen_img:
                        if (scenceHomeBean.getData().getList().get(position).getEndTime()==null){
                            return;
                        }else {
                            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            Date one;
                            Date two;
                            long day = 0;
                            long hour = 0;
                            long min = 0;
                            long sec = 0;
                            try {
                                //1 当前时间 ，2到期时间
                                Date curDate = new Date(System.currentTimeMillis());//获取当前时间
                                String str = df.format(curDate);
                                one = df.parse(str);
                                two = df.parse(scenceHomeBean.getData().getList().get(position).getEndTime());
                                long time1 = one.getTime();
                                long time2 = two.getTime();
                                long diff;
                                if (time1 > time2) {
                                    ToastUtil.showToast(getActivity(),"该场景已过期");
                                    return;

                                }
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                        }
                      //  SharedPreferenceUtil.SaveData("merchatname",scenceHomeBean.getData().getMerchantName());
                        if (DateUtils.isFastClick()) {
                            return ;
                        }
                        startActivity(new Intent(getActivity(), VrWebActivity.class)
                                .putExtra("urls", scenHomeAdapter.getItem(position).getSceneUrl())
                                .putExtra("type", "2")
                                .putExtra("names", scenHomeAdapter.getItem(position).getSceneName())
                                .putExtra("scenid", scenHomeAdapter.getItem(position).getSceneId() + "")
                                .putExtra("storenodeid", scenHomeAdapter.getItem(position).getStoreNodeId() + "")
                                .putExtra("storeid", scenceHomeBean.getData().getMerchantId() + "")
                                //.putExtra("shops", scenHomeAdapter.getItem(position).getStoreName() + "")
                              .putExtra("shops", scenceHomeBean.getData().getMerchantName() + "")
                        );

                        break;
                }
            }
        });
    }

    /**
     * string转成bitmap *  * @param st
     */
    public static Bitmap convertStringToIcon(String st) {
        // OutputStream out;
        Bitmap bitmap = null;
        try {
            OutputStream out = new FileOutputStream(st);
            byte[] bitmapArray;
            String replace = st.replace("data:image/jpeg;base64,", "");
            bitmapArray = Base64.decode(replace, Base64.DEFAULT);
            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length, null);
            bitmap.compress(Bitmap.CompressFormat.PNG, 60, out);
            return bitmap;
        } catch (Exception e) {
            return null;
        }
    }

    //分享弹窗
    private void showBottomDialog(int i) {
        //1、使用Dialog、设置style
        final Dialog dialog = new Dialog(getActivity(), R.style.DialogTheme);
        //2、设置布局
        View view = View.inflate(getActivity(), R.layout.wx_shar_popu, null);
        TextView fxname = view.findViewById(R.id.fx_name);
        fxname.setText(scenceHomeBean.getData().getList().get(i).getSceneName());
        dialog.setContentView(view);

        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.BOTTOM);
        //设置弹出动画
        window.setWindowAnimations(R.style.main_menu_animStyle);
        //设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();
      //微信分享
        dialog.findViewById(R.id.wx_shars).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                picUrl = scenceHomeBean.getData().getList().get(i).getPicUrl();
                sceneUrl = scenceHomeBean.getData().getList().get(i).getSceneUrl();
                sceneId = scenceHomeBean.getData().getList().get(i).getSceneId();
                scenname=scenceHomeBean.getData().getList().get(i).getSceneName();
                storename=scenceHomeBean.getData().getList().get(i).getStoreName()+"";
                bitmap = returnBitMap(picUrl);
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// HH:mm:ss
                Date date = new Date(System.currentTimeMillis());
                cloudCustomDataBean = new UserVrBean.CloudCustomDataBean(
                        "SHARE",
                        SharedPreferenceUtil.getStringData("tonodeid")
                        , sceneId
                        , scenname
                        , scenceHomeBean.getData().getList().get(i).getStoreNodeId()
                        , storename
                        , SharedPreferenceUtil.getStringData("staffid")
                        , SharedPreferenceUtil.getStringData("staffname")
                        , "1"
                        , ""
                        , ""
                        , "0", simpleDateFormat.format(date));
                V2TIMMessage v2TIMMessage = V2TIMManager.getMessageManager().createCustomMessage(sceneId.getBytes());
                // 发送消息
                String msgs = JSON.toJSONString(cloudCustomDataBean);
                v2TIMMessage.setCloudCustomData(msgs);
                V2TIMManager.getMessageManager().sendMessage(v2TIMMessage, "cid_1", null, V2TIMMessage.V2TIM_PRIORITY_DEFAULT, false, null, new V2TIMSendCallback<V2TIMMessage>() {
                    @Override
                    public void onError(int code, String desc) {
                        Log.e("SHARE", code + "" + desc);
                    }

                    @Override
                    public void onSuccess(V2TIMMessage v2TIMMessage) {
                        Log.e("SHARE", "onSuccess");
                    }

                    @Override
                    public void onProgress(int progress) {
                        Log.e("SHARE", "progress");
                    }
                });


                mHandler.sendEmptyMessageDelayed(10, 1000);
                // popupWindow.dismiss();

            }
        });

        dialog.findViewById(R.id.hb_shars).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                sceneId = scenceHomeBean.getData().getList().get(i).getSceneId();
//                scenname=scenceHomeBean.getData().getList().get(i).getSceneName();
//                storename=scenceHomeBean.getData().getList().get(i).getStoreName()+"";
                startActivity(new Intent(getActivity(), PosterActivity.class)
                        .putExtra("img", scenceHomeBean.getData().getList().get(i).getPicUrl() + "")
                        .putExtra("shar", "" + scenceHomeBean.getData().getList().get(i).getSceneUrl())
                        .putExtra("scenname", "" + scenceHomeBean.getData().getList().get(i).getSceneName()+"")
                        .putExtra("storeid", "" + scenceHomeBean.getData().getList().get(i).getStoreNodeId()+"")
                        .putExtra("storename", "" + scenceHomeBean.getData().getList().get(i).getStoreName()+"")
                        .putExtra("scenid", "" + scenceHomeBean.getData().getList().get(i).getSceneId()+""));

                dialog.dismiss();
            }

        });

        dialog.findViewById(R.id.shar_dismis).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

    }


    @Override
    public <T> T request(int requestFlag) {
        return null;
    }

    @Override
    public <T> void response(T response, int responseFlag) {
        if (responseFlag == IScenHomeFramentFView.RESPONSE_ONE) {
            scenceHomeBean = (ScenceHomeBean) response;

            if (scenceHomeBean.getCode() == 0) {
             if (scenceHomeBean.getData().getList().size()==0){
                 oneyy.setVisibility(View.GONE);
                 llTodaytwo.setVisibility(View.VISIBLE);
                 return;
             }else {
                 oneyy.setVisibility(View.VISIBLE);
                 llTodaytwo.setVisibility(View.GONE);
             }
             SharedPreferenceUtil.SaveData("merchat",scenceHomeBean.getData().getMerchantName());
                scenHomeAdapter.setNewData(scenceHomeBean.getData().getList());
                scenHomeAdapter.notifyDataSetChanged();
                company.setText(scenceHomeBean.getData().getMerchantName() + " 共 " + scenceHomeBean.getData().getClassicSceneCount() + "个场景");
            } else {
                ToastUtil.showToast(getActivity(), scenceHomeBean.getMsg() + "");
            }

        }
    }


    //弹窗
    private void initpopu(View v) {
        View contentView = LayoutInflater.from(getActivity()).inflate(
                R.layout.popu_scen, null);
        Button share = (Button) contentView.findViewById(R.id.share);
        Button browse = (Button) contentView.findViewById(R.id.browse);
        Button metting = (Button) contentView.findViewById(R.id.metting);
        Button time = (Button) contentView.findViewById(R.id.time);
        //分享数量
        share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvScreen.setText("分享次数");
                ///    Glide.with(getActivity()).load(R.mipmap.down_item).into(scenFh);
                popupWindow.dismiss();
                mIScenHomeFramentFPresenter.getLscenhome("share");
                scenHomeAdapter.notifyDataSetChanged();
            }
        });
        //浏览数量
        browse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvScreen.setText("浏览次数");
                ///     Glide.with(getActivity()).load(R.mipmap.down_item).into(scenFh);
                popupWindow.dismiss();
                mIScenHomeFramentFPresenter.getLscenhome("browse");
                scenHomeAdapter.notifyDataSetChanged();
            }
        });
        //同屏讲解次数
        metting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvScreen.setText("同屏讲解次数");
                ///      Glide.with(getActivity()).load(R.mipmap.down_item).into(scenFh);
                popupWindow.dismiss();
                mIScenHomeFramentFPresenter.getLscenhome("meeting");
                scenHomeAdapter.notifyDataSetChanged();
            }
        });
        //上传时间
        time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvScreen.setText("上传时间");
                ///       Glide.with(getActivity()).load(R.mipmap.down_item).into(scenFh);
                popupWindow.dismiss();
                mIScenHomeFramentFPresenter.getLscenhome("time");
                scenHomeAdapter.notifyDataSetChanged();
            }
        });
        popupWindow = new PopupWindow(contentView,
                330, ViewGroup.LayoutParams.WRAP_CONTENT, true);

        popupWindow.setTouchable(true);

        popupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                //   Log.i("mengdd", "onTouch : ");

                return false;
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss

            }
        });
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                scenFh.animate().setDuration(500).rotation(0).start();
            }
        });
        // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
        // 我觉得这里是API的一个bug
        popupWindow.setBackgroundDrawable(getResources().getDrawable(
                R.drawable.baise));

        // 设置好参数之后再show
        popupWindow.showAsDropDown(v);
        //      popupWindow.showAtLocation(tvScreen, Gravity.BOTTOM,0,0);
        //  Glide.with(getActivity()).load(R.mipmap.down_item).into(scenFh);
    }

    //图片转换
    public Bitmap returnBitMap(final String url) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                URL imageurl = null;

                try {
                    imageurl = new URL(url);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                try {
                    HttpURLConnection conn = (HttpURLConnection) imageurl.openConnection();
                    conn.setDoInput(true);
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    bitmap = BitmapFactory.decodeStream(is);
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        return bitmap;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (scenHomeAdapter != null) {
            scenHomeAdapter.cancelAllTimers();
        }
    }

    @OnClick(R.id.tv_return)
    public void onViewClicked() {
        getActivity().finish();
    }
}
